package controllers

import (
	"LoginTemplate/models"
)

type ClientController struct {
	BaseController
}

type Client struct {
	ID                    int     `json:"id"`
	ClientName            string  `json:"client_name"`
	ClientPhone           string  `json:"client_phone"`
	ClientClassify        string  `json:"client_classify"`
	Time                  string  `json:"time"`
	ClientFollow          string  `json:"client_follow"`
	PromoterId            int     `json:"promoter_id"`
	CommunityId           int     `json:"community_id"`
	DateBirth             string  `json:"date_birth"`
	NativePlace           string  `json:"native_place"`
	Address               string  `json:"address"`
	Gender                string  `json:"gender"`
	IdCard                string  `json:"id_card"`
	Age                   int     `json:"age"`
	Nation                string  `json:"nation"`
	HealthyCondition      string  `json:"healthy_condition"`
	MaritalStatus         string  `json:"marital_status"`
	PoliticsStatus        string  `json:"politics_status"`
	Children              string  `json:"children"`
	Like                  string  `json:"like"`
	EducationBackground   string  `json:"education_background"`
	PhysicalExamination   string  `json:"physical_examination"`
	Faith                 string  `json:"faith"`
	NotEat                string  `json:"not_eat"`
	Occupation            string  `json:"occupation"`
	Unit                  string  `json:"unit"`
	OnJob                 string  `json:"on_job"`
	OwnHouse              string  `json:"own_house"`
	Counselor             string  `json:"counselor"`
	Company               string  `json:"company"`
	Recreation            string  `json:"recreation"`
	Investment            string  `json:"investment"`
	GeneralSituation      string  `json:"general_situation"`
	SpecificCircumstance  string  `json:"specific_circumstance"`
	SubmissionTime        string  `json:"submission_time"`
	Money                 string  `json:"money"`
	EmergencyContactOne   string  `json:"emergency_contact_one"`
	EmergencyContactTwo   string  `json:"emergency_contact_two"`
	InterestPoint         string  `json:"interest_point"`
	Network               string  `json:"network"`
	PresentationCondition string  `json:"presentation_condition"`
	OneMeet               string  `json:"one_meet"`
	Insight               string  `json:"insight"`
	Audit                 int     `json:"audit"`
	Balance               float64 `json:"balance"`
	Integral              int     `json:"integral"`
	City                  string  `json:"city"`
}

// 添加分类
func (u *ClientController) InsertClient() {
	var client Client
	err := u.ShouldBind(&client)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into client ( client_name,client_phone,client_classify,`time`,client_follow,promoter_id,community_id,date_birth,native_place,address,gender,id_card,age,nation,healthy_condition,marital_status,politics_status,children,`like`,education_background,physical_examination,faith,not_eat,occupation,unit,on_job,own_house,counselor,company,recreation,investment,general_situation,specific_circumstance,submission_time,money,emergency_contact_one,emergency_contact_two,interest_point,network,presentation_condition,one_meet,insight ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )"
	tx := models.DB.Debug().Exec(sql, client.ClientName, client.ClientPhone, client.ClientClassify, client.Time, client.ClientFollow, client.PromoterId, client.CommunityId, client.DateBirth, client.NativePlace, client.Address, client.Gender, client.IdCard, client.Age, client.Nation, client.HealthyCondition,
		client.MaritalStatus, client.PoliticsStatus, client.Children, client.Like, client.EducationBackground, client.PhysicalExamination, client.Faith, client.NotEat, client.Occupation, client.Unit, client.OnJob,
		client.OwnHouse, client.Counselor, client.Company, client.Recreation, client.Investment, client.GeneralSituation, client.SpecificCircumstance, client.SubmissionTime, client.Money, client.EmergencyContactOne, client.EmergencyContactTwo,
		client.InterestPoint, client.Network, client.PresentationCondition, client.OneMeet, client.Insight)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改分类
func (u *ClientController) UpdateClient() {
	var client Client
	err := u.ShouldBind(&client)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update client set client_name = ?,client_phone = ?,client_classify = ?,time = ? ,client_follow = ? ,promoter_id = ? ,community_id = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, client.ClientName, client.ClientPhone, client.ClientClassify, client.Time, client.ClientFollow, client.PromoterId, client.CommunityId, client.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type ClientData struct {
	Code        int      `json:"code"`
	Msg         string   `json:"msg"`
	Data        []Client `json:"data"`
	Sum         int      `json:"sum"`         //总页数
	CurrentPage int      `json:"currentPage"` //当前页
	TotalNumber int      `json:"totalNumber"` //总条数
}
type ClientList struct {
	Page  int `json:"page"`
	Size  int `json:"size"`
	Id    int `json:"id"`
	Audit int `json:"audit"`
}

// 查询分类
func (u *ClientController) SelectClient() {
	var pictureList ClientList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var client []Client
	if pictureList.Audit != 0 {
		sql := "select * from client where `audit` = ? limit ? , ?"
		tx := models.DB.Debug().Raw(sql, pictureList.Audit, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&client)
		if tx.Error != nil {
			u.JsonMsg(500, "", "请求异常，请稍候再试")
		}
		sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM client where `audit` = ?"
		models.DB.Debug().Raw(sqlsum, pictureList.Size, pictureList.Audit).Scan(&sum)
		sqlNumBer := "select count(*) from client where `audit` = ?"
		models.DB.Debug().Raw(sqlNumBer, pictureList.Audit).Scan(&totalNumber)
	} else {
		sql := "select * from client limit ? , ?"
		tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&client)
		if tx.Error != nil {
			u.JsonMsg(500, "", "请求异常，请稍候再试")
		}
		sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM client"
		models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
		sqlNumBer := "select count(*) from client"
		models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	}
	var picturedata ClientData
	picturedata.Code = 200
	picturedata.Data = client
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}

type PromoterId struct {
	Id int `json:"id"`
}

// 查询我的客户人数
func (u *ClientController) SelectMyClientSum() {
	//var promoterId PromoterId
	var sum int
	var promoterId PromoterId
	err := u.ShouldBind(&promoterId)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "select count(*) from client where promoter_id = ?"
	models.DB.Debug().Raw(sql, promoterId.Id).Scan(&sum)
	u.JsonMsg(200, map[string]interface{}{
		"list":  sum,
		"count": "",
	}, "success")
}

// 查询我的欠款客户人数
func (u *ClientController) SelectMyDebtClientSum() {
	//var promoterId PromoterId
	var sum int
	var promoterId PromoterId
	err := u.ShouldBind(&promoterId)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "select count(*) from client where promoter_id = ? and client_classify = 3"
	models.DB.Debug().Raw(sql, promoterId.Id).Scan(&sum)
	u.JsonMsg(200, map[string]interface{}{
		"list":  sum,
		"count": "",
	}, "success")
}

type MareLiBeRum struct {
	City string `json:"city"`
}

// 查询公海
func (u *ClientController) SelectMareLiBeRum() {
	var promoterId MareLiBeRum
	err := u.ShouldBind(&promoterId)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var client []Client
	sql := "select * from client where client_classify = 2 and city = ?"
	models.DB.Debug().Raw(sql, promoterId.City).Scan(&client)
	u.JsonMsg(200, map[string]interface{}{
		"list":  client,
		"count": "",
	}, "success")
}
